//useDialogForm.js
import {
    ref, nextTick, reactive
} from "vue";
import {deepClone} from "../libs/utils";

/**
 * @param apiFuncs
 * @param formProps
 * @param formRef
 */
export default function (apiFuncs, formProps = [], formRef) {
    if (!apiFuncs) {
        apiFuncs = {
            detailFun: () => Promise.resolve(),
            postDataFun: () => Promise.resolve(),
        }
    }
    const {detailFun, postDataFun} = apiFuncs
    const visible = ref(false)

    function initFormProps() {
        const form = {}
        if (formProps && formProps.length > 0) {
            for (let i = 0, len = formProps.length; i < len; i++) {
                form[formProps[i]] = ''
            }
        }
        return form;
    }

    const dataForm = reactive(initFormProps())

    function resetFormFields(data) {
        const keys = Object.keys(data);
        for (let i = 0, len = keys.length; i < len; i++) {
            const key = keys[i];
            dataForm[key] = data[key];
        }
    }

    function openDialog() {
        visible.value = true
    }

    function closeDialog() {
        formRef.value.resetFields()
        // resetFields生效了，但是我们的el-form里面并没有全部的field，比如id这样的并没有放进去，那么到时候dataForm的id还是留下来了
        resetFormFields(initFormProps())
        visible.value = false
    }

    function beforeClose(done) {
        done()
        formRef.value.resetFields()
    }

    function doGetDetail(id) {
        return detailFun(id)
            .then((resp) => {
                //获取返回数据
                if (resp.code === 200) {
                    resetFormFields(resp.data)
                }
                return Promise.resolve(resp.data)
            })
            .catch((e) => {
                // eslint-disable-next-line
                console.error(e)
                return Promise.reject(e)
            });
    }

    // 新增 / 修改的弹窗
    function doAddOrUpdateHandle(id) {
        if (id) {
            return nextTick(() => {
                return doGetDetail(id)
            })
        } else {
            // initFormProps();
            return Promise.resolve(dataForm)
        }
    }

    // 表单提交
    function doDataFormSubmit() {
        const postData = deepClone(dataForm)
        return postDataFun(postData)
            .then((resp) => {//获取返回数据
                if (resp.code === 200) {
                    // 进行一些其它的处理
                }
                closeDialog();
                return Promise.resolve(resp)
            }).catch((e) => {
                // eslint-disable-next-line
                console.error(e)
                return Promise.reject(e)
            });
    }

    function init(id) {
        openDialog();
        return doAddOrUpdateHandle(id);
    }

    return {
        visible,
        dataForm,
        doDataFormSubmit,
        doGetDetail,
        doAddOrUpdateHandle,
        init,
        beforeClose
    }
}

